package auth

import (
	"gitee.com/aldrice/monitor/ent"
	"gitee.com/aldrice/monitor/ent/user"
	"gitee.com/aldrice/monitor/internal/router"
	"gitee.com/aldrice/monitor/pkg/crypto"
)

type userLoginReq struct {
	Username string `json:"username" validate:"required"`
	Password string `json:"password" validate:"required"`
}

var (
	errInvalidUsername = router.ApiError(10000, "invalid username")
	errInvalidPassword = router.ApiError(10002, "invalid password")
)

func Login(c *router.Context) error {
	req := new(userLoginReq)
	if err := c.Bind(req); err != nil {
		return err
	}
	if err := c.Validate(req); err != nil {
		return err
	}

	db, ctx := c.DB(), c.Ctx()

	u, err := db.User.Query().Where(user.UsernameEqualFold(req.Username)).First(ctx)
	if err != nil {
		if ent.IsNotFound(err) {
			return errInvalidUsername
		}
		return err
	}

	// crypto the password then store it into db
	isRight := crypto.ComparePassword(req.Password, u.Password)
	if !isRight {
		return errInvalidPassword
	}

	// send user jwt
	if err := sendUserAuthToken(c, u.ID); err != nil {
		return err
	}

	return c.ApiSuccess(c.Response().Header().Get("x-issued-token"))
}
